﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Genuilder.Extensibility.TestProject.Gen.Dependency;
using Genuilder.Extensibility.NRefactory;
using ICSharpCode.NRefactory.Visitors;
using ICSharpCode.NRefactory.Ast;
using ICSharpCode.NRefactory.PrettyPrinter;


namespace Genuilder.Extensibility.TestProject.Gen
{

	public class MagicReflectionPlugin : IPlugin
	{
		#region IPlugin Members

		ICodeRepository _Repository;
		public void Initialize(ICodeRepository repository)
		{
			_Repository = repository;
			repository.CodeItemCreated += new CodeItemCreatedHandler(repository_CodeTracked);
		}

		void repository_CodeTracked(CodeItem item)
		{
			if(item.Name.EndsWith("gen.cs"))
				return;
			var dependency = new CodeDependency(item, _Repository.Add(item.Name + "gen.cs"));
			dependency.ShouldUpdateTarget += new CodeDependencyHandler(dependency_ShouldUpdateTarget);

		}

		void dependency_ShouldUpdateTarget(CodeDependency sender, CodeItem target)
		{
			var source = sender.Source;
			var compiledSource = source.GetExtension<CompilationUnitExtension>();
			if(compiledSource.Errors.Count > 0)
				return;
			var sourceDom = compiledSource.CompilationUnit;
			MagicReflectionVisitor visitor = new MagicReflectionVisitor();
			var compilationUnit = (CompilationUnit)visitor.VisitCompilationUnit(sourceDom, null);
			if(compilationUnit != null)
			{
				CSharpOutputVisitor cSharpOutput = new CSharpOutputVisitor();
				cSharpOutput.VisitCompilationUnit(compilationUnit, null);
				target.Content = cSharpOutput.Text;
			}
			else
			{
				target.Delete();
			}
		}

		#endregion
	}


}
